<template>
	<login-register>
		<el-form class="login_bodybox" ref="loginForm" :rules="formRules" :model="loginForm">
			<el-form-item prop="account">
				<el-input
					auto-complete="new-password"
					prefix-icon="el-icon-sw-user"
					placeholder="请输入您的登录账号"
					v-model="loginForm.account"
					@keyup.enter.native="handleSubmitLogin"
				></el-input>
			</el-form-item>
			<el-form-item prop="password">
				<el-input
					show-password
					auto-complete="new-password"
					prefix-icon="el-icon-sw-password"
					placeholder="请输入您的登录密码"
					v-model="loginForm.password"
					@keyup.enter.native="handleSubmitLogin"
				></el-input>
			</el-form-item>
			<el-form-item prop="imageCode" class="image-code" v-if="!!isShowVerifyCode">
				<el-input
					type="text"
					maxlength="4"
					prefix-icon="el-icon-sw-verfycode"
					placeholder="请输入验证码"
					v-model="loginForm.imageCode"
					@input="verifyCodeFormat"
					@keyup.enter.native="handleSubmitLogin"
				></el-input>
				<template v-if="!!verifyCodeImg">
					<img class="code" :src="verifyCodeImg" @click="getVerifyCode" />
				</template>
			</el-form-item>
			<el-form-item class="button">
				<el-button type="primary" @click="handleSubmitLogin" :loading="btnLoading">立即登录</el-button>
			</el-form-item>
			<el-form-item class="link">
				<span>暂无账号，马上</span>
				<router-link to="/register" replace>注册</router-link>
			</el-form-item>
		</el-form>
	</login-register>
</template>

<script>
import md5 from 'js-md5';
import loginRegister from './common/loginRegister';
import { login, addUserInfo } from '@/api/loginRegister';
import { generateVerifyCode, loginAddUserInfo } from '@/api/global';
export default {
	consts: ['VAILCODE'],
	components: { loginRegister },
	data() {
		const validImageCode = (rule, value, callback) => {
			try {
				if (!value) {
					callback(new Error('请输入验证码'));
				} else if (this.verifyCode !== value) {
					callback(new Error('请输入正确的验证码'));
				} else {
					callback();
				}
			} catch (error) {
				callback(error);
			}
		};
		return {
			loading: false,
			siteName: '',
			verifyCode: '',
			verifyCodeImg: '',
			loginForm: {},
			formRules: {
				account: [{ required: true, message: '请输入用户账号', trigger: 'blur' }],
				password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }],
				imageCode: [{ required: true, validator: validImageCode, trigger: 'blur' }]
			},
			btnLoading: false
		};
	},
	computed: {
		isShowVerifyCode() {
			let vailcode = this.dictData['VAILCODE'];
			return !!vailcode && vailcode === '1';
		}
	},
	watch: {
		isShowVerifyCode(flag) {
			if (!flag) return false;
			this.getVerifyCode();
		}
	},
	methods: {
		//提交登录
		handleSubmitLogin() {
			this.$refs['loginForm'].validate((vail) => {
				if (!vail) return false;
				this.btnLoading = true;
				this.loginRequest(this.loginForm).then(async (data) => {
					await this.$store.dispatch('getAuthMenu', data.id);
					await this.$store.dispatch('getCourseLabel');
					await this.$store.dispatch('getDepartList');
					this.$message.success('登录成功');
					await addUserInfo(data.id);
					this.btnLoading = false;
					if (!this.$route.query.redirect) {
						this.$router.replace('/front');
					} else {
						this.$router.replace(this.$route.query.redirect);
					}
				});
			});
		},

		//登录请求
		async loginRequest(data) {
			let pass = md5(data.password + this.md5Key);
			let params = { ...data, password: pass.toUpperCase() };
			let result = await login(params).then((res) => res);
			let resultData = result.data;
			if (resultData.code === 0) {
				let datas = this.$detailData(resultData.data);
				let httpUrl = datas?.sysAttachment?.httpUrl;
				let userInfo = { ...datas, avatarImg: httpUrl?.replaceIP() };
				let authorization = result.headers['authorization'];
				this.$store.commit('SET_TOKEN', authorization);
				this.$store.commit('SET_USER_INFO', userInfo);
				return Promise.resolve(userInfo);
			} else {
				this.btnLoading = false;
				this.getVerifyCode();
			}
		},

		//获取验证码
		async getVerifyCode() {
			let result = await generateVerifyCode().then((res) => res.data);
			if (result.code === '0') {
				let datas = this.$detailData(result.data);
				this.verifyCode = datas.code;
				this.verifyCodeImg = datas.base64String;
			}
		},

		//大写转化
		verifyCodeFormat(value) {
			this.loginForm.imageCode = value.toUpperCase().replace(/[^A-Z0-9]/g, '');
		}
	}
};
</script>

<style lang="scss" scoped></style>
